package org.liveboardgames.agricola.control.delegates
{
	import com.adobe.cairngorm.business.ServiceLocator;

	import mx.collections.ListCollectionView;
	import mx.rpc.IResponder;

	import org.liveboardgames.agricola.control.delegates.helper.GameHelper;
	import org.liveboardgames.agricola.control.delegates.mock.FarmFactory;
	import org.liveboardgames.agricola.model.AgricolaModelLocator;
	import org.liveboardgames.agricola.model.enums.ResourceTypeEnum;
	import org.liveboardgames.agricola.vo.farm.Farm;
	import org.liveboardgames.agricola.vo.farm.FarmTile;
	import org.liveboardgames.agricola.vo.farm.Pasture;
	import org.liveboardgames.common.dictionary.collections.HashCollection;
	import org.liveboardgames.common.dictionary.collections.IMap;

	public class BuildPastureDelegate
	{
		private var _responder:IResponder;

		private var _service:Object;

		public function BuildPastureDelegate(responder:IResponder)
		{
			this._service = ServiceLocator.getInstance().getRemoteObject("pastureService");
			this._responder = responder;
		}

		public function buildPasture(farm:Farm, tileIDs:ListCollectionView):void
		{
			var call:Object = _service.buildPasture(AgricolaModelLocator.getInstance().game.id, farm.id, tileIDs);
			call.resultHandler = _responder.result;
			call.faultHandler = _responder.fault;
//            setTimeout(buildPastureService, 0, farm, tiles);
		}

		private function buildPastureService(farm:Farm, tiles:ListCollectionView):void
		{
			var fencesBuilt:ListCollectionView = GameHelper.getNewFences(farm, tiles);

			// Pay the fences
			var woodCost:int = fencesBuilt.length;
			var cost:IMap = new HashCollection();
			cost.put(ResourceTypeEnum.WOOD, woodCost);
			GameHelper.pay(farm, cost);

			// Build the new pastures
			var newPasture:Pasture = FarmFactory.getNewPasture(farm);
			for each (var pastureTile:FarmTile in tiles)
			{
				pastureTile.pasture = newPasture;
			}

			// Compute new number of available fences
			_responder.result(GameHelper.computeAvailableFences(farm));
		}
	}
}